﻿using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.GameState;
using TaleWorlds.CampaignSystem.Inventory;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Localization;

namespace MarriageFertility.Helpers;

  public class HeroDiyEquipment
    {
        private ItemRoster _stash;
        private PartyBase _leftParty;
        private int _woundedNumber;
        
        /// <summary>
        /// 创建临时英雄、初始化背包、打开交易界面
        /// </summary>
        public void Create(Hero hero)
        {
            // 初始化物品仓库
            InitStashItem();

            // 打开自定义装备的交易界面
            OpenTrade(hero);
        }

       
        /// <summary>
        /// 初始化物品仓库并添加所有装备类物品
        /// </summary>
        private void InitStashItem()
        {
            _stash = new ItemRoster();
        }

        /// <summary>
        /// 打开交易界面，并设置交易完成后的回调逻辑
        /// </summary>
        private void OpenTrade(Hero hero)
        {
        
                if (!hero.HasMet)
                {
                    hero.SetHasMet();
                }
          
            var backupPlayerItemRoster = new ItemRoster(MobileParty.MainParty.ItemRoster);
            var originalItemTypes = new Dictionary<ItemRosterElement, ItemObject.ItemTypeEnum>();

            
                // 初始化临时交易方，将仓库中的所有物品添加进去
                _leftParty = new PartyBase(Settlement.CurrentSettlement);
                foreach (var item in _stash)
                {
                    if (item.Amount > 0 && !item.IsEmpty && !_leftParty.ItemRoster.Contains(item))
                    {
                        _leftParty.ItemRoster.AddToCounts(item.EquipmentElement, item.Amount);
                    }
                }

                // 遍历玩家物品，将符合条件的物品记录原始类型并暂时置为 Invalid（以便交易时使用）
                foreach (var item in MobileParty.MainParty.ItemRoster)
                {
                    if (item.Amount > 0)
                    {
                        EquipmentElement equipmentElement = item.EquipmentElement;
                        if (!equipmentElement.Equals(EquipmentElement.Invalid) &&
                            !equipmentElement.Item.IsCraftedByPlayer &&
                            equipmentElement.Item.ItemType != ItemObject.ItemTypeEnum.Goods)
                        {
                            originalItemTypes.Add(item, equipmentElement.Item.ItemType);
                            LogicArms.SetNotPublicPro(equipmentElement.Item, "ItemType", ItemObject.ItemTypeEnum.Invalid);
                        }
                    }
                }

                // 设置库存管理器为交易模式，并初始化逻辑
                LogicArms.SetNotPublicVar(InventoryManager.Instance, "_currentMode", InventoryMode.Trade);
                var inventoryLogic = new InventoryLogic(null);
                LogicArms.SetNotPublicVar(InventoryManager.Instance, "_inventoryLogic", inventoryLogic);

                var troopRoster = new TroopRoster(MobileParty.MainParty.Party);
              
                    // troopRoster.AddToCounts(hero.CharacterObject, 1);
             
                inventoryLogic.Initialize(
                    _leftParty.ItemRoster,
                    MobileParty.MainParty.ItemRoster,
                    troopRoster,
                    false,
                    false,
                    hero.CharacterObject,
                    InventoryManager.InventoryCategoryType.All,
                    Settlement.All.Find(s=>s.IsTown).Town.MarketData,
                    false,
                    new TextObject("{=MF_CustomerEquipment}MF_Customer Equipment"));

                // 设置交易完成后的回调委托
                LogicArms.SetNotPublicVar(InventoryManager.Instance, "_doneLogicExtrasDelegate", new InventoryManager.DoneLogicExtrasDelegate(() =>
                {
                    OnTradeCompleted(hero, backupPlayerItemRoster, originalItemTypes);
                }));

                InventoryState state = Game.Current.GameStateManager.CreateState<InventoryState>();
                state.InitializeLogic(inventoryLogic);
                Game.Current.GameStateManager.PushState(state);
        }

        /// <summary>
        /// 交易完成后的处理逻辑
        /// </summary>
        private void OnTradeCompleted(Hero hero, ItemRoster backupPlayerItemRoster, Dictionary<ItemRosterElement, ItemObject.ItemTypeEnum> originalItemTypes)
        {
            try
            {
                // 清理交易用的临时数据
                _leftParty = null;
                RestoreOriginalItemTypes(originalItemTypes);

                // 处理多余物品（如果有）
                List<ItemRosterElement> extraItems = GetExtraItems(backupPlayerItemRoster, MobileParty.MainParty.ItemRoster);
                foreach (var extraItem in extraItems)
                {
                    if (MobileParty.MainParty.ItemRoster.Contains(extraItem))
                    {
                        MobileParty.MainParty.ItemRoster.Remove(extraItem);
                    }
                }
                RemoveTemporaryHeroFromRoster(hero.CharacterObject);
            }
            catch (Exception ex)
            {
               Log.ErrorMessage(ex.ToString());
            }
        }

        /// <summary>
        /// 恢复玩家物品中曾被置为 Invalid 的物品类型
        /// </summary>
        private void RestoreOriginalItemTypes(Dictionary<ItemRosterElement, ItemObject.ItemTypeEnum> originalItemTypes)
        {
            foreach (var kvp in originalItemTypes)
            {
                ItemRosterElement originalElement = kvp.Key;
                foreach (var item in MobileParty.MainParty.ItemRoster)
                {
                    if (originalElement.Equals(item))
                    {
                        LogicArms.SetNotPublicPro(item.EquipmentElement.Item, "ItemType", kvp.Value);
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 将临时英雄从部队成员名册中移除
        /// </summary>
        private void RemoveTemporaryHeroFromRoster(CharacterObject troopCharacterObject)
        {
            TroopRoster memberRoster = MobileParty.MainParty.MemberRoster;
            foreach (TroopRosterElement troop in memberRoster.GetTroopRoster())
            {
                if (troop.Character.StringId.Equals(troopCharacterObject.StringId))
                {
                    memberRoster.RemoveTroop(troop.Character);
                    break;
                }
            }
        }

        /// <summary>
        /// 比较交易前后的物品仓库，找出多余的物品（逻辑可能根据实际需求调整）
        /// </summary>
        private List<ItemRosterElement> GetExtraItems(ItemRoster backupRoster, ItemRoster currentRoster)
        {
            var extraItems = new List<ItemRosterElement>();

            if (backupRoster.Count == 0)
            {
                extraItems.AddRange(currentRoster);
            }
            else
            {
                foreach (var backupItem in backupRoster)
                {
                    foreach (var currentItem in currentRoster)
                    {
                        if (!backupItem.IsEmpty && !currentItem.IsEmpty && !backupRoster.Contains(currentItem))
                        {
                            extraItems.Add(currentItem);
                        }
                        if (!backupItem.IsEmpty && !currentItem.IsEmpty)
                        {
                            EquipmentElement backupEquipment = backupItem.EquipmentElement;
                            EquipmentElement currentEquipment = currentItem.EquipmentElement;
                            if (backupEquipment.Item.Equals(currentEquipment.Item) &&
                                backupEquipment.ItemModifier == currentEquipment.ItemModifier &&
                                backupItem.Amount < currentItem.Amount)
                            {
                                // 若当前物品数量超过备份数量，则将差额添加（或移除）以达到一致
                                int difference = backupItem.Amount - currentItem.Amount;
                                currentRoster.AddToCounts(currentEquipment.Item, difference);
                            }
                        }
                    }
                }
            }

            return extraItems;
        }

       
    }